package cn.javaxxw.zxing.spring.boot.utils;

import com.google.zxing.FormatException;

/**
 * @author tuy
 * @description 工具类
 * @date 2021/1/21 16:28
 */
public class BarCodeUtils {

    /**
     * EAN（国际标准条码）计算校验码
     * <p>如果是UPC算法，需要在前面补一个0</p>
     * @param s 去掉最后一位的数字字符串
     * @return 一位校验码
     * @throws FormatException 非数字异常
     * @see com.google.zxing.oned.UPCEANReader
     */
    public static int getUpcEanChecksum(CharSequence s) throws FormatException {
        int length = s.length();
        int sum = 0;
        for (int i = length - 1; i >= 0; i -= 2) {
            int digit = s.charAt(i) - '0';
            if (digit < 0 || digit > 9) {
                throw FormatException.getFormatInstance();
            }
            sum += digit;
        }
        sum *= 3;
        for (int i = length - 2; i >= 0; i -= 2) {
            int digit = s.charAt(i) - '0';
            if (digit < 0 || digit > 9) {
                throw FormatException.getFormatInstance();
            }
            sum += digit;
        }
        return (1000 - sum) % 10;
    }
}
